import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/models.dart';
import '../services/services.dart';
import '../constants/constants.dart';
import 'player_screen.dart';

/// 播放历史页面
/// 显示用户的播放历史记录
class HistoryScreen extends StatefulWidget {
  const HistoryScreen({super.key});

  @override
  State<HistoryScreen> createState() => _HistoryScreenState();
}

class _HistoryScreenState extends State<HistoryScreen>
    with TickerProviderStateMixin {
  late AnimationController _fadeController;
  late Animation<double> _fadeAnimation;

  List<PlayHistory> _historyList = [];
  List<Music> _musicList = [];
  bool _isLoading = true;
  HistoryFilter _currentFilter = HistoryFilter.all;

  @override
  void initState() {
    super.initState();
    _initAnimations();
    _loadHistory();
  }

  /// 初始化动画
  void _initAnimations() {
    _fadeController = AnimationController(
      duration: AppTheme.animationDurationMedium,
      vsync: this,
    );
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fadeController,
      curve: Curves.easeInOut,
    ));
  }

  /// 加载播放历史
  Future<void> _loadHistory() async {
    try {
      final databaseService =
          Provider.of<DatabaseService>(context, listen: false);
      final musicLibraryService =
          Provider.of<MusicLibraryService>(context, listen: false);

      // 获取播放历史
      final history = await databaseService.getPlayHistory(
        limit: 100,
      );

      // 获取对应的音乐信息
      final musicIds = history.map((h) => h.musicId).toSet().toList();
      final musicList = <Music>[];
      for (final musicId in musicIds) {
        Music? music;
        try {
          music = musicLibraryService.musicLibrary.firstWhere(
            (m) => m.id == musicId,
          );
        } catch (e) {
          music = null;
        }
        if (music != null) {
          musicList.add(music);
        }
      }

      setState(() {
        _historyList = history;
        _musicList = musicList;
        _isLoading = false;
      });

      _fadeController.forward();
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      _showErrorSnackBar('加载播放历史失败: $e');
    }
  }

  /// 获取过滤条件
  String? _getFilterCondition() {
    switch (_currentFilter) {
      case HistoryFilter.today:
        final today = DateTime.now();
        final startOfDay = DateTime(today.year, today.month, today.day);
        return 'play_time >= ${startOfDay.millisecondsSinceEpoch}';
      case HistoryFilter.thisWeek:
        final now = DateTime.now();
        final startOfWeek = now.subtract(Duration(days: now.weekday - 1));
        final startOfWeekDay =
            DateTime(startOfWeek.year, startOfWeek.month, startOfWeek.day);
        return 'play_time >= ${startOfWeekDay.millisecondsSinceEpoch}';
      case HistoryFilter.thisMonth:
        final now = DateTime.now();
        final startOfMonth = DateTime(now.year, now.month, 1);
        return 'play_time >= ${startOfMonth.millisecondsSinceEpoch}';
      case HistoryFilter.all:
      default:
        return null;
    }
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: AppTheme.errorColor,
      ),
    );
  }

  @override
  void dispose() {
    _fadeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: AppTheme.backgroundGradientDark,
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部标题栏
              _buildHeader(),

              // 过滤器
              _buildFilterTabs(),

              // 历史列表
              Expanded(
                child: _isLoading
                    ? _buildLoadingState()
                    : _historyList.isEmpty
                        ? _buildEmptyState()
                        : _buildHistoryList(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(AppTheme.spacingMedium),
      child: Row(
        children: [
          // IconButton(
          //   onPressed: () => Navigator.of(context).pop(),
          //   icon: const Icon(
          //     Icons.arrow_back,
          //     color: AppTheme.textPrimaryDark,
          //     size: AppTheme.iconSizeLarge,
          //   ),
          // ),
          const Expanded(
            child: Text(
              '播放历史',
              style: TextStyle(
                fontSize: AppTheme.fontSizeXL,
                fontWeight: FontWeight.bold,
                color: AppTheme.textPrimaryDark,
              ),
            ),
          ),
          if (_historyList.isNotEmpty)
            IconButton(
              onPressed: _showClearHistoryDialog,
              icon: const Icon(
                Icons.delete_outline,
                color: AppTheme.textSecondaryDark,
                size: AppTheme.iconSizeLarge,
              ),
            ),
        ],
      ),
    );
  }

  /// 构建过滤器标签
  Widget _buildFilterTabs() {
    return Container(
      height: 50,
      margin: const EdgeInsets.symmetric(horizontal: AppTheme.spacingMedium),
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: HistoryFilter.values.map((filter) {
          final isSelected = _currentFilter == filter;
          return Container(
            margin: const EdgeInsets.only(right: AppTheme.spacingSmall),
            child: FilterChip(
              label: Text(
                _getFilterTitle(filter),
                style: TextStyle(
                  color: isSelected ? Colors.white : AppTheme.textSecondaryDark,
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                ),
              ),
              selected: isSelected,
              onSelected: (selected) {
                if (selected) {
                  setState(() {
                    _currentFilter = filter;
                    _isLoading = true;
                  });
                  _loadHistory();
                }
              },
              selectedColor: AppTheme.primaryColor,
              backgroundColor: AppTheme.surfaceDark,
              side: BorderSide(
                color: isSelected
                    ? AppTheme.primaryColor
                    : AppTheme.primaryColor.withOpacity(0.3),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  /// 构建加载状态
  Widget _buildLoadingState() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
          ),
          SizedBox(height: AppTheme.spacingMedium),
          Text(
            '正在加载播放历史...',
            style: TextStyle(
              fontSize: AppTheme.fontSizeMedium,
              color: AppTheme.textSecondaryDark,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: AppTheme.albumCoverSizeLarge,
            height: AppTheme.albumCoverSizeLarge,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: AppTheme.surfaceDark,
              border: Border.all(
                color: AppTheme.primaryColor.withOpacity(0.3),
                width: 2,
              ),
            ),
            child: const Icon(
              Icons.history,
              size: AppTheme.iconSizeXL,
              color: AppTheme.textHintDark,
            ),
          ),
          const SizedBox(height: AppTheme.spacingLarge),
          Text(
            _getEmptyStateTitle(),
            style: const TextStyle(
              fontSize: AppTheme.fontSizeLarge,
              color: AppTheme.textSecondaryDark,
            ),
          ),
          const SizedBox(height: AppTheme.spacingMedium),
          const Text(
            '开始播放音乐来记录你的\n播放历史',
            style: TextStyle(
              fontSize: AppTheme.fontSizeMedium,
              color: AppTheme.textHintDark,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: AppTheme.spacingXL),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: const Text('浏览音乐库'),
          ),
        ],
      ),
    );
  }

  /// 构建历史列表
  Widget _buildHistoryList() {
    return FadeTransition(
      opacity: _fadeAnimation,
      child: Column(
        children: [
          // 统计信息
          Container(
            margin: const EdgeInsets.all(AppTheme.spacingMedium),
            padding: const EdgeInsets.all(AppTheme.spacingMedium),
            decoration: BoxDecoration(
              color: AppTheme.surfaceDark,
              borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
              border: Border.all(
                color: AppTheme.primaryColor.withOpacity(0.3),
                width: 1,
              ),
            ),
            child: Row(
              children: [
                const Icon(
                  Icons.history,
                  color: AppTheme.primaryColor,
                  size: AppTheme.iconSizeMedium,
                ),
                const SizedBox(width: AppTheme.spacingSmall),
                Text(
                  '共 ${_historyList.length} 条播放记录',
                  style: const TextStyle(
                    fontSize: AppTheme.fontSizeMedium,
                    color: AppTheme.textPrimaryDark,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const Spacer(),
                Text(
                  _getTotalPlayTime(),
                  style: const TextStyle(
                    fontSize: AppTheme.fontSizeSmall,
                    color: AppTheme.textSecondaryDark,
                  ),
                ),
              ],
            ),
          ),

          // 历史记录列表
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.symmetric(
                horizontal: AppTheme.spacingMedium,
              ),
              itemCount: _historyList.length,
              itemBuilder: (context, index) {
                final history = _historyList[index];
                final music = _musicList.firstWhere(
                  (m) => m.id == history.musicId,
                  orElse: () => Music(
                    id: history.musicId,
                    title: '未知音乐',
                    artist: '未知艺术家',
                    filePath: '',
                    duration: 0,
                    fileSize: 0,
                    createdAt: DateTime.now(),
                    updatedAt: DateTime.now(),
                  ),
                );
                return _buildHistoryItem(history, music, index);
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建历史记录项
  Widget _buildHistoryItem(PlayHistory history, Music music, int index) {
    return Consumer<AudioPlayerService>(
      builder: (context, audioService, child) {
        final isCurrentMusic = audioService.currentMusic?.id == music.id;
        final isPlaying = isCurrentMusic && audioService.isPlaying;

        return Container(
          margin: const EdgeInsets.only(bottom: AppTheme.spacingSmall),
          decoration: BoxDecoration(
            color: isCurrentMusic
                ? AppTheme.primaryColor.withOpacity(0.1)
                : AppTheme.surfaceDark,
            borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
            border: isCurrentMusic
                ? Border.all(
                    color: AppTheme.primaryColor.withOpacity(0.5),
                    width: 1,
                  )
                : null,
          ),
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(
              horizontal: AppTheme.spacingMedium,
              vertical: AppTheme.spacingSmall,
            ),
            leading: _buildMusicCover(music, isPlaying),
            title: Text(
              music.title,
              style: TextStyle(
                fontSize: AppTheme.fontSizeMedium,
                fontWeight:
                    isCurrentMusic ? FontWeight.w600 : FontWeight.normal,
                color: isCurrentMusic
                    ? AppTheme.primaryColor
                    : AppTheme.textPrimaryDark,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  music.artist,
                  style: const TextStyle(
                    fontSize: AppTheme.fontSizeSmall,
                    color: AppTheme.textSecondaryDark,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 2),
                Row(
                  children: [
                    Text(
                      history.formattedPlayDuration,
                      style: const TextStyle(
                        fontSize: AppTheme.fontSizeXS,
                        color: AppTheme.textHintDark,
                      ),
                    ),
                    const Text(
                      ' • ',
                      style: TextStyle(
                        fontSize: AppTheme.fontSizeXS,
                        color: AppTheme.textHintDark,
                      ),
                    ),
                    Text(
                      '播放 ${history.formattedPlayDuration}',
                      style: const TextStyle(
                        fontSize: AppTheme.fontSizeXS,
                        color: AppTheme.textHintDark,
                      ),
                    ),
                    if (history.completed) ...[
                      const Text(
                        ' • ',
                        style: TextStyle(
                          fontSize: AppTheme.fontSizeXS,
                          color: AppTheme.textHintDark,
                        ),
                      ),
                      const Text(
                        '完整播放',
                        style: TextStyle(
                          fontSize: AppTheme.fontSizeXS,
                          color: AppTheme.successColor,
                        ),
                      ),
                    ],
                  ],
                ),
              ],
            ),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                if (history.progress > 0)
                  Container(
                    width: 40,
                    height: 4,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(2),
                      color: AppTheme.primaryColor.withOpacity(0.3),
                    ),
                    child: FractionallySizedBox(
                      alignment: Alignment.centerLeft,
                      widthFactor: history.progress,
                      child: Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(2),
                          color: AppTheme.primaryColor,
                        ),
                      ),
                    ),
                  ),
                const SizedBox(width: AppTheme.spacingSmall),
                IconButton(
                  onPressed: () => _showHistoryOptions(history, music),
                  icon: const Icon(
                    Icons.more_vert,
                    color: AppTheme.textSecondaryDark,
                    size: AppTheme.iconSizeMedium,
                  ),
                ),
              ],
            ),
            onTap: () => _playMusic(music),
          ),
        );
      },
    );
  }

  /// 构建音乐封面
  Widget _buildMusicCover(Music music, bool isPlaying) {
    return Container(
      width: AppTheme.albumCoverSizeMedium,
      height: AppTheme.albumCoverSizeMedium,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
        gradient: AppTheme.primaryGradient,
      ),
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
            child: music.coverArt != null
                ? Image.asset(
                    music.coverArt!,
                    width: AppTheme.albumCoverSizeMedium,
                    height: AppTheme.albumCoverSizeMedium,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return _buildDefaultMusicCover();
                    },
                  )
                : _buildDefaultMusicCover(),
          ),
          if (isPlaying)
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
                color: Colors.black.withOpacity(0.5),
              ),
              child: const Center(
                child: Icon(
                  Icons.equalizer,
                  color: AppTheme.primaryColor,
                  size: AppTheme.iconSizeMedium,
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 构建默认音乐封面
  Widget _buildDefaultMusicCover() {
    return Container(
      width: AppTheme.albumCoverSizeMedium,
      height: AppTheme.albumCoverSizeMedium,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
        gradient: AppTheme.primaryGradient,
      ),
      child: const Icon(
        Icons.music_note,
        color: Colors.white,
        size: AppTheme.iconSizeMedium,
      ),
    );
  }

  /// 获取过滤器标题
  String _getFilterTitle(HistoryFilter filter) {
    switch (filter) {
      case HistoryFilter.all:
        return '全部';
      case HistoryFilter.today:
        return '今天';
      case HistoryFilter.thisWeek:
        return '本周';
      case HistoryFilter.thisMonth:
        return '本月';
    }
  }

  /// 获取空状态标题
  String _getEmptyStateTitle() {
    switch (_currentFilter) {
      case HistoryFilter.today:
        return '今天还没有播放记录';
      case HistoryFilter.thisWeek:
        return '本周还没有播放记录';
      case HistoryFilter.thisMonth:
        return '本月还没有播放记录';
      case HistoryFilter.all:
      default:
        return '暂无播放历史';
    }
  }

  /// 获取总播放时长
  String _getTotalPlayTime() {
    final totalSeconds = _historyList.fold<int>(
      0,
      (sum, history) => sum + history.playDuration,
    );

    final hours = totalSeconds ~/ 3600;
    final minutes = (totalSeconds % 3600) ~/ 60;

    if (hours > 0) {
      return '$hours小时$minutes分钟';
    } else {
      return '$minutes分钟';
    }
  }

  /// 播放音乐
  void _playMusic(Music music) {
    final audioService =
        Provider.of<AudioPlayerService>(context, listen: false);

    // 播放单首音乐
    audioService.playMusic(music);

    // 导航到播放页面
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const PlayerScreen(),
      ),
    );
  }

  /// 显示历史记录选项
  void _showHistoryOptions(PlayHistory history, Music music) {
    showModalBottomSheet(
      context: context,
      backgroundColor: AppTheme.surfaceDark,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(AppTheme.radiusLarge),
        ),
      ),
      builder: (context) => _buildHistoryOptionsBottomSheet(history, music),
    );
  }

  /// 构建历史记录选项底部表单
  Widget _buildHistoryOptionsBottomSheet(PlayHistory history, Music music) {
    return Container(
      padding: const EdgeInsets.all(AppTheme.spacingMedium),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 音乐信息
          ListTile(
            leading: _buildMusicCover(music, false),
            title: Text(
              music.title,
              style: const TextStyle(
                fontSize: AppTheme.fontSizeMedium,
                fontWeight: FontWeight.w600,
                color: AppTheme.textPrimaryDark,
              ),
            ),
            subtitle: Text(
              '${music.artist} • ${history.formattedPlayDuration}',
              style: const TextStyle(
                fontSize: AppTheme.fontSizeSmall,
                color: AppTheme.textSecondaryDark,
              ),
            ),
          ),

          const Divider(color: AppTheme.dividerDark),

          // 选项列表
          ListTile(
            leading: const Icon(
              Icons.play_arrow,
              color: AppTheme.primaryColor,
            ),
            title: const Text(
              '播放',
              style: TextStyle(color: AppTheme.textPrimaryDark),
            ),
            onTap: () {
              Navigator.of(context).pop();
              _playMusic(music);
            },
          ),
          ListTile(
            leading: const Icon(
              Icons.delete_outline,
              color: AppTheme.errorColor,
            ),
            title: const Text(
              '删除此记录',
              style: TextStyle(color: AppTheme.textPrimaryDark),
            ),
            onTap: () {
              Navigator.of(context).pop();
              _deleteHistoryItem(history);
            },
          ),
        ],
      ),
    );
  }

  /// 显示清空历史对话框
  void _showClearHistoryDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: AppTheme.surfaceDark,
        title: const Text(
          '清空播放历史',
          style: TextStyle(color: AppTheme.textPrimaryDark),
        ),
        content: Text(
          '确定要清空${_getFilterTitle(_currentFilter)}的播放历史吗？\n此操作无法撤销。',
          style: const TextStyle(color: AppTheme.textSecondaryDark),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text(
              '取消',
              style: TextStyle(color: AppTheme.textSecondaryDark),
            ),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _clearHistory();
            },
            child: const Text(
              '确定',
              style: TextStyle(color: AppTheme.errorColor),
            ),
          ),
        ],
      ),
    );
  }

  /// 清空历史记录
  void _clearHistory() async {
    try {
      final databaseService =
          Provider.of<DatabaseService>(context, listen: false);

      if (_currentFilter == HistoryFilter.all) {
        await databaseService.clearTable('play_history');
      } else {
        final condition = _getFilterCondition();
        if (condition != null) {
          await databaseService.deletePlayHistory(condition);
        }
      }

      setState(() {
        _historyList.clear();
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('播放历史已清空'),
            backgroundColor: AppTheme.successColor,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar('清空失败: $e');
      }
    }
  }

  /// 删除历史记录项
  void _deleteHistoryItem(PlayHistory history) async {
    try {
      final databaseService =
          Provider.of<DatabaseService>(context, listen: false);
      await databaseService.deletePlayHistory('id = ${history.id}');

      setState(() {
        _historyList.removeWhere((h) => h.id == history.id);
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('记录已删除'),
            backgroundColor: AppTheme.successColor,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar('删除失败: $e');
      }
    }
  }
}

/// 历史记录过滤器枚举
enum HistoryFilter {
  all,
  today,
  thisWeek,
  thisMonth,
}
